package com.xbongbong.crm.perform.command.delete;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.crm.abstracts.AbstractCrmDeleteService;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasProcessDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.elasticsearch.model.PaasEsModel;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.help.CommonHelp;
import com.xbongbong.paas.log.MongoLogHelp;
import com.xbongbong.paas.log.constant.LogMemoConstant;
import com.xbongbong.paas.log.pojo.InfoArrPojo;
import com.xbongbong.paas.model.PaasProcessDataModel;
import com.xbongbong.paas.pojo.dto.FormDataDeleteBatchDTO;
import com.xbongbong.paas.pojo.vo.FormDataDeleteBatchVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.ConstantUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.parent.pojo.delete.ErrorDataPojo;
import com.xbongbong.pro.constant.ElasticConstant;
import com.xbongbong.pro.contractproduct.pojo.dto.ContractProductDeleteBatchDTO;
import com.xbongbong.pro.contractsurcharge.pojo.dto.ContractSurchargeDeteleBatchDTO;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.message.model.PushModel;
import com.xbongbong.pro.payment.pojo.dto.PaymentDeleteBatchDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.ErrorMessageConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.InvoiceRelationshipEntity;
import com.xbongbong.saas.domain.entity.ext.ContractEntityExt;
import com.xbongbong.saas.enums.OperateModuleTypeEnum;
import com.xbongbong.saas.enums.OperateTypeEnum;
import com.xbongbong.saas.enums.OutstockTypeEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.business.OutstockEnum;
import com.xbongbong.saas.enums.business.PaymentEnum;
import com.xbongbong.saas.enums.business.PaymentSheetEnum;
import com.xbongbong.saas.enums.business.RefundEnum;
import com.xbongbong.saas.help.FundHelp;
import com.xbongbong.saas.model.ContractModel;
import com.xbongbong.saas.model.ContractPerformanceModel;
import com.xbongbong.saas.model.ContractProductModel;
import com.xbongbong.saas.model.ContractSurchargeModel;
import com.xbongbong.saas.model.ContractUserModel;
import com.xbongbong.saas.model.InvoiceRelationshipModel;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * @author 吴峰
 * @date 2022/05/23 9:30
 */
@Service("contractDeleteServiceImpl")
public class ContractDeleteServiceImpl extends AbstractCrmDeleteService<PaasFormEntityExt, ContractEntityExt> {
    @Resource
    private ContractModel contractModel;
    @Resource
    private PaasEsModel paasEsModel;
    @Resource
    private PaasProcessDataModel paasProcessDataModel;
    @Resource
    private CommonHelp commonHelp;
    @Resource
    private EsHelper esHelper;
    @Resource
    private FundHelp fundHelp;
    @Resource
    private InvoiceRelationshipModel invoiceRelationshipModel;
    @Resource
    private ContractPerformanceModel contractPerformanceModel;
    @Resource
    private ContractProductModel contractProductModel;
    @Resource
    private ContractSurchargeModel contractSurchargeModel;
    @Resource
    private ContractUserModel contractUserModel;
    @Resource
    private PushModel pushModel;
    @Resource
    private MongoLogHelp mongoLogHelp;

    @Override
    public List<Integer> businessType() {
        return Arrays.asList(XbbRefTypeEnum.CONTRACT.getCode());
    }


    @Override
    public FormDataDeleteBatchVO deleteWorkflow(FormDataDeleteBatchDTO formDataDeleteBatchDTO) throws XbbException {
        List<Long> contactIdIn = formDataDeleteBatchDTO.getDataIdList();
        String corpid = formDataDeleteBatchDTO.getCorpid();
        contractModel.deleteBatch(contactIdIn, corpid);
        contractUserModel.deleteByContractIdIn(contactIdIn, corpid);

        contractProductModel.deleteContractAllProduct(contactIdIn, corpid, DelEnum.DELETE.getDel());
        return new FormDataDeleteBatchVO();
    }

    @Override
    public FormDataDeleteBatchVO deleteBatchNoPermission(FormDataDeleteBatchDTO formDataDeleteBatchDTO, PaasFormEntityExt form) throws XbbException {
        List<ContractEntityExt> list = deleteEsData(formDataDeleteBatchDTO, formDataDeleteBatchDTO.getDataIdList(), formDataDeleteBatchDTO.getCorpid());
        ErrorDataPojo errorDataPojo = notAllowData(formDataDeleteBatchDTO, list);

        List<Long> deleteIdIn = deleteData(formDataDeleteBatchDTO, errorDataPojo.getDeleteList(), list, formDataDeleteBatchDTO.getCorpid());
        log(formDataDeleteBatchDTO, list, errorDataPojo);
        return new FormDataDeleteBatchVO(errorDataPojo.getErrorDataList(), errorDataPojo.getErrorTypeList(), errorDataPojo.getErrorDataMemo(), deleteIdIn);
    }

    @Override
    public List<ContractEntityExt> deleteEsData(FormDataDeleteBatchDTO formDataDeleteBatchDTO, List<Long> dataIdIn, String corpid) throws XbbException {
        // 过滤不允许删除的客户
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put("idIn", dataIdIn);
        param.put("del", DelEnum.NORMAL.getDel());
        List<ContractEntityExt> list = contractModel.findEntitys(param);
        if (Objects.isNull(list)) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        //兼容删除脏数据
        if (!Objects.equals(dataIdIn.size(), list.size())) {
            list = paasEsModel.getByIdList(dataIdIn, corpid, null, IndexTypeEnum.IDX_SAAS_CONTRACT, ContractEntityExt.class);
        }
        return list;
    }

    @Override
    public ErrorDataPojo notAllowData(FormDataDeleteBatchDTO formDataDeleteBatchDTO, List<ContractEntityExt> list) throws XbbException {

        String corpid = formDataDeleteBatchDTO.getCorpid();
        List<Long> deleteIdIn = new ArrayList<>();
        list.forEach(item->{
            deleteIdIn.add(item.getId());
        });
        //paymentSheetInApprove之前表示在审批阶段的回款单，现在表示只要存在审批中的回款单，或存在回款单就不能删除
        List<Long> paymentSheetInApprove = new ArrayList<>();
        if (commonHelp.isOpenWorkFlow(corpid)) {
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termsQuery(PaymentSheetEnum.getEsAttr4Keyword(PaymentSheetEnum.CONTRACT), deleteIdIn));
            boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.APPROVAL_PENDING.getType(), FlowStatusEnum.IN_APPROVAL.getType())));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET.getType()));
            List<PaasFormDataEntityExt> paymentSheetFormDataList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PAYMENT_SHEET,
                    boolQueryBuilder, PaasFormDataEntityExt.class, Arrays.asList(PaymentSheetEnum.getAttrConnectData(PaymentSheetEnum.CONTRACT), FieldTypeEnum.DATAID.getAlias()));
            paymentSheetFormDataList.forEach(item -> {
                JSONObject data = item.getData();
                if (Objects.nonNull(data)) {
                    JSONArray contractIds = data.getJSONArray(PaymentSheetEnum.CONTRACT.getAttr());
                    for (Object obj : contractIds) {
                        if (Objects.nonNull(obj)) {
                            Long contractId = StringUtil.StringToLong(obj.toString());
                            if (Objects.nonNull(contractId)) {
                                paymentSheetInApprove.add(contractId);
                            }
                        }
                    }
                }
            });
        } else {
            List<PaasProcessDataEntity> paymentSheetProcessList = paasProcessDataModel.getInApprovalDataByIdConditionJsonArray(XbbRefTypeEnum.PAYMENT_SHEET.getCode(), PaymentSheetEnum.CONTRACT.getAttr(), deleteIdIn, corpid, Arrays.asList(FlowStatusEnum.APPROVAL_PENDING.getType(), FlowStatusEnum.IN_APPROVAL.getType()));
            if (Objects.isNull(paymentSheetProcessList)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
            }
            paymentSheetProcessList.forEach(item -> {
                JSONObject data = JSON.parseObject(item.getData());
                if (Objects.nonNull(data)) {
                    JSONArray contractIds = data.getJSONArray(PaymentSheetEnum.CONTRACT.getAttr());
                    for (Object obj : contractIds) {
                        if (Objects.nonNull(obj)) {
                            Long contractId = StringUtil.StringToLong(obj.toString());
                            if (Objects.nonNull(contractId)) {
                                paymentSheetInApprove.add(contractId);
                            }
                        }
                    }
                }
            });
        }
        List<Object> linkIdIn = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        deleteIdIn.forEach(id->{
            linkIdIn.add(id);
        });
        Map<Long, PaasFormDataEntityExt> paymentSheetEntityExtMap = fundHelp.getEsDataMapByLinkIds(XbbRefTypeEnum.PAYMENT_SHEET, corpid, linkIdIn, PaymentSheetEnum.CONTRACT.getAttr());
        for (ContractEntityExt item : list) {
            Long contractId = item.getId();
            PaasFormDataEntityExt paymentSheetEntityExt = paymentSheetEntityExtMap.get(contractId);
            if (Objects.nonNull(paymentSheetEntityExt)) {
                paymentSheetInApprove.add(contractId);
            }
        }
        // 查询合同还有没有关联的退货退款单 youli.chen 未关联退货退款的正常删除

        Set<Long> linkRefundId = new HashSet<>();
        List<String> field = new ArrayList<>();
        List<PaasFormDataEntityExt> entityExts;
        // 查询合同还有没有关联的退货退款单 未关联退货退款的正常删除
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder queryBuilder = boolQuery();
        queryBuilder.filter(termQuery("corpid.keyword", corpid));
        queryBuilder.filter(termsQuery("data." + RefundEnum.CONTRACT_ID.getAttr(), deleteIdIn));
        queryBuilder.filter(termQuery("del", 0));
        // 设置join_field
        queryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_REFUND.getType()));
        sourceBuilder.query(queryBuilder);
        field.add(RefundEnum.CONTRACT_ID.getAttr());
        entityExts = paasEsModel.list(sourceBuilder, IndexTypeEnum.IDX_SAAS_REFUND, field, null, null);
        if (Objects.nonNull(entityExts)) {
            for (PaasFormDataEntityExt entity : entityExts) {
                JSONObject data = entity.getData();
                Long contractId = data.getLong(RefundEnum.CONTRACT_ID.getAttr());
                linkRefundId.add(contractId);
            }
        }

        //paymentSheetInApprove之前表示在审批阶段的回款单，现在表示只要存在审批中的回款单，或存在回款单就不能删除
        List<Long> invoiceInApprove = new ArrayList<>();
        if (commonHelp.isOpenWorkFlow(corpid)) {
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
            boolQueryBuilder.filter(termsQuery(PaymentSheetEnum.getEsAttr4Keyword(PaymentSheetEnum.CONTRACT), deleteIdIn));
            boolQueryBuilder.filter(termsQuery("flowStatus", Arrays.asList(FlowStatusEnum.APPROVAL_PENDING.getType(), FlowStatusEnum.IN_APPROVAL.getType())));
            boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_INVOICE.getType()));
            List<PaasFormDataEntityExt> invoiceFormDataList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_INVOICE,
                    boolQueryBuilder, PaasFormDataEntityExt.class, Arrays.asList(PaymentSheetEnum.getAttrConnectData(PaymentSheetEnum.CONTRACT), FieldTypeEnum.DATAID.getAlias()));
            invoiceFormDataList.forEach(item -> {
                JSONObject data = item.getData();
                if (Objects.nonNull(data)) {
                    JSONArray contractIds = data.getJSONArray(PaymentSheetEnum.CONTRACT.getAttr());
                    for (Object obj : contractIds) {
                        Long contractId = StringUtil.StringToLong((String) obj);
                        if (Objects.nonNull(contractId)) {
                            invoiceInApprove.add(contractId);
                        }
                    }
                }
            });
        } else {
            // 获取销项发票是否在审批中
            List<PaasProcessDataEntity> invoiceProcessList = paasProcessDataModel.getInvoiceInApprovalDataByIdConditionJsonArray(XbbRefTypeEnum.INVOICE.getCode(), PaymentSheetEnum.CONTRACT.getAttr(), deleteIdIn, corpid, Arrays.asList(FlowStatusEnum.APPROVAL_PENDING.getType(), FlowStatusEnum.IN_APPROVAL.getType()));
            invoiceProcessList.forEach(item -> {
                JSONObject data = JSON.parseObject(item.getData());
                if (Objects.nonNull(data)) {
                    JSONArray contractIds = data.getJSONArray(PaymentSheetEnum.CONTRACT.getAttr());
                    for (Object obj : contractIds) {
                        Long contractId = StringUtil.StringToLong((String) obj);
                        if (Objects.nonNull(contractId)) {
                            invoiceInApprove.add(contractId);
                        }
                    }
                }
            });
        }

        Map<String, Object> map = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        map.put("contractIdIn", deleteIdIn);
        map.put("corpid", corpid);
        map.put("del", DelEnum.NORMAL);
        List<InvoiceRelationshipEntity> invoiceRelationshipEntityList = invoiceRelationshipModel.findEntitys(map);
        Set<Long> invoiceRelationshipContractList = new HashSet<>();
        Map<Long, Long> contractRefInvoiceId = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        invoiceRelationshipEntityList.forEach(invoiceRelationshipEntity -> {
            invoiceRelationshipContractList.add(invoiceRelationshipEntity.getContractId());
            contractRefInvoiceId.put(invoiceRelationshipEntity.getContractId(), invoiceRelationshipEntity.getInvoiceId());
        });


        List<Long> physicalDelIds = new ArrayList<>();
        physicalDelIds.addAll(deleteIdIn);
        // 查询合同是否有下游单据销售出库单，生成了关联销售出库单的不允许删除
        Set<Long> linkOutstackId = new HashSet<>();
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termsQuery("data." + OutstockEnum.REF_ID.getAttr(), deleteIdIn));
        boolQueryBuilder.filter(termQuery("data." + OutstockEnum.TYPE.getAttr(), OutstockTypeEnum.CONTRACT_OUTSTOCK.getCode()));
        boolQueryBuilder.filter(termQuery("del", 0));
        // 设置join_field
        boolQueryBuilder.filter(termQuery(ElasticConstant.MY_JOIN_FIELD, IndexTypeEnum.IDX_SAAS_CONTRACT_OUTSTOCK.getType()));
        sourceBuilder.query(boolQueryBuilder);
        field.clear();
        field.add(OutstockEnum.REF_ID.getAttr());
        entityExts = paasEsModel.list(sourceBuilder, IndexTypeEnum.IDX_SAAS_CONTRACT_OUTSTOCK, field, null, null);

        if (Objects.nonNull(entityExts)) {
            for (PaasFormDataEntityExt entity : entityExts) {
                JSONObject data = entity.getData();
                Long contractId = data.getLong(OutstockEnum.REF_ID.getAttr());
                linkOutstackId.add(contractId);
            }
        }
        List<String> errorDataList = new ArrayList<>();
        Set<String> errorDataSet = new HashSet<>();
        Set<String> errorTypeSet = new HashSet<>();
        List<String> errorTypeList = new ArrayList<>();


        // 未关联退货退款的合同ID
        deleteIdIn.removeAll(linkRefundId);
        deleteIdIn.removeAll(linkOutstackId);
        for (ContractEntityExt item : list) {
            JSONObject contractObj = item.getData();
            if (linkRefundId.contains(item.getId())) {
                errorTypeSet.add(String.format(I18nMessageUtil.getMessage(ErrorMessageConstant.HAVE_REFUND_NOT_DEL), XbbRefTypeEnum.CONTRACT.getName()));
                errorDataSet.add(item.getSerialNo());
            }
            // 合同关联销售出库单，不允许删除
            if (linkOutstackId.contains(item.getId())) {
                errorTypeSet.add(String.format(I18nMessageUtil.getMessage(ErrorMessageConstant.HAVE_OUTSTACK_NOT_DEL), XbbRefTypeEnum.CONTRACT.getName()));
                errorDataSet.add(item.getSerialNo());
            }
            // 回款单存在审批中的，不允许删除
            if (paymentSheetInApprove.contains(item.getId())) {
                deleteIdIn.remove(item.getId());
                errorTypeSet.add(I18nMessageUtil.getMessage(ErrorMessageConstant.HAVE_PAYMENT_SHEET_NOT_DEL));
                errorDataSet.add(item.getSerialNo());
            }

            if (invoiceInApprove.contains(item.getId())) {
                deleteIdIn.remove(item.getId());
                errorTypeSet.add(I18nMessageUtil.getMessage(ErrorMessageConstant.HAVE_INVOICE_APPROVE_NOT_DEL));
                errorDataSet.add(item.getSerialNo());
            }
            if (invoiceRelationshipContractList.contains(item.getId())) {
                //Long invoiceId = contractRefInvoiceId.getOrDefault(item.getId(),0L);
                deleteIdIn.remove(item.getId());
                errorTypeSet.add(String.format(I18nMessageUtil.getMessage(ErrorMessageConstant.HAVE_CONTRACT_INVOICE_NOT_DEL), XbbRefTypeEnum.CONTRACT.getName()));
                errorDataSet.add(item.getSerialNo());
            }
        }
        errorDataList.addAll(errorDataSet);
        errorTypeList.addAll(errorTypeSet);
        return new ErrorDataPojo(errorDataList, errorTypeList, ConstantUtil.getErrorDataMemo(errorTypeList, errorDataList), deleteIdIn);
    }

    @Override
    public List<Long> deleteData(FormDataDeleteBatchDTO formDataDeleteBatchDTO, List<Long> deleteIdIn, List<ContractEntityExt> list, String corpid) throws XbbException {
        if (!deleteIdIn.isEmpty()) {
            if (BasicConstant.ONE.equals(formDataDeleteBatchDTO.getSingleFlag())
                    && BasicConstant.ONE.equals(deleteIdIn.size())) {
                contractModel.deleteByKey(deleteIdIn.get(0), corpid);
            } else {
                contractModel.deleteBatch(deleteIdIn, corpid);
            }
            // 删除合同联系人
            contractUserModel.deleteByContractIdIn(deleteIdIn, corpid);
        }

        // 删除相关应收款
        if (!deleteIdIn.isEmpty()) {
            BoolQueryBuilder booleanQuery = boolQuery();
            booleanQuery.filter(termsQuery(StringConstant.JSON_DATA + StringConstant.POINT + PaymentEnum.CONTRACT.getAttr(), deleteIdIn));
            booleanQuery.filter(termQuery(StringConstant.CORPID + StringConstant.POINT + StringConstant.KEY_WORD, corpid));
            booleanQuery.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
            List<String> fieldList = new ArrayList<>();
            fieldList.add(FieldTypeEnum.DATAID.getAlias());
            List<PaasFormDataEntityExt> paymentList = esHelper.findByScroll(IndexTypeEnum.IDX_SAAS_PAYMENT, booleanQuery, PaasFormDataEntityExt.class, fieldList);
            if (Objects.isNull(paymentList)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
            List<Long> paymentIdIn = new ArrayList<>();
            paymentList.forEach((item) -> {
                paymentIdIn.add(item.getDataId());
            });
            if (!paymentIdIn.isEmpty()) {
                PaymentDeleteBatchDTO paymentDeleteBatchDTO = new PaymentDeleteBatchDTO();
                BeanUtil.copyProperties(formDataDeleteBatchDTO, paymentDeleteBatchDTO, true);
                paymentDeleteBatchDTO.setDataIdList(paymentIdIn);
                // TODO 回款单待处理
                // paymentService.deleteBatch(paymentDeleteBatchDTO);
            }
            // 删除合同业绩分配
            contractPerformanceModel.deleteByContractIdIn(deleteIdIn, corpid);
            // 删除合同产品
            ContractProductDeleteBatchDTO contractProductDeleteBatchDTO = new ContractProductDeleteBatchDTO();
            BeanUtil.copyProperties(formDataDeleteBatchDTO, contractProductDeleteBatchDTO, true);
            contractProductDeleteBatchDTO.setContractIdIn(deleteIdIn);
            contractProductModel.deleteContractAllProduct(deleteIdIn, corpid, DelEnum.DELETE.getDel());
            // 删除合同的其他费用
            ContractSurchargeDeteleBatchDTO contractSurchargeDeteleBatchDTO = new ContractSurchargeDeteleBatchDTO();
            BeanUtil.copyProperties(formDataDeleteBatchDTO, contractSurchargeDeteleBatchDTO, true);
            contractSurchargeDeteleBatchDTO.setContractIdIn(deleteIdIn);
            contractSurchargeModel.deleteBatchByContractId(deleteIdIn, corpid);
            // 删除提醒
            pushModel.deletePushNotify(deleteIdIn, corpid, XbbRefTypeEnum.CONTRACT.getCode());
        }
        return deleteIdIn;
    }

    @Override
    public void log(FormDataDeleteBatchDTO formDataDeleteBatchDTO, List<ContractEntityExt> list, ErrorDataPojo errorDataPojo) throws XbbException {
        Map<String, String> noAndName = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        for (ContractEntityExt item : list) {
            String no = item.getSerialNo();
            String name = FastJsonHelper.getStringOrDefaultFromFormData(item.getData(), ContractEnum.NAME.getAttr(), "");
            noAndName.put(no, name);
        }
        //生成删除日志(区分单个删除和批量删除)
        String userId = formDataDeleteBatchDTO.getUserId();
        String userName = formDataDeleteBatchDTO.getLoginUserName();
        List<String> logNameList = new ArrayList<>();
        Iterator<String> iterator = noAndName.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            String value = noAndName.get(key);
            if (StringUtil.isEmpty(value)) {
                logNameList.add(key);
            } else {
                StringBuilder sb = new StringBuilder();
                sb.append(key).append("（").append(value).append("）");
                logNameList.add(sb.toString());
            }
        }
        OperateTypeEnum operateTypeEnum = OperateTypeEnum.DELETE;
        if (Objects.equals(1, formDataDeleteBatchDTO.getIsBusinessRule())) {
            operateTypeEnum = OperateTypeEnum.RULE_DELETE;
        }
        String nameStr = StringUtils.join(logNameList, "，");
        List<Long> deleteIdIn = errorDataPojo.getDeleteList();
        String corpid = formDataDeleteBatchDTO.getCorpid();
        if (deleteIdIn.size() > 1) {
            String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_BATCH_DELETE_FORM_DETAIL), userName, XbbRefTypeEnum.CONTRACT.getName(), deleteIdIn.size());
            List<InfoArrPojo> infoArrPojoList = new ArrayList<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            InfoArrPojo infoArrPojo = new InfoArrPojo();
            infoArrPojo.setTitle(ContractEnum.CONTRACT_NO.getAttrName());
            infoArrPojo.setContent(nameStr);
            infoArrPojoList.add(infoArrPojo);
            mongoLogHelp.buildLog4InfoArr(infoArrPojoList, corpid, userId, userName, OperateModuleTypeEnum.CONTRACT, operateTypeEnum,
                    "", "", memo, formDataDeleteBatchDTO.getHttpHeader());
        } else if (Objects.equals(deleteIdIn.size(), 1)) {
            String memo = String.format(I18nMessageUtil.getMessage(LogMemoConstant.LOG_MEMO_USER_DELETE_WORK), userName, XbbRefTypeEnum.CONTRACT.getName(), nameStr);
            mongoLogHelp.buildLog(corpid, userId, userName, OperateModuleTypeEnum.CONTRACT, operateTypeEnum,
                    deleteIdIn.get(0).toString(), nameStr, memo, formDataDeleteBatchDTO.getHttpHeader());
        }
    }

    @Override
    public void deleteAfter(List<Long> dataIdList, FormDataDeleteBatchDTO formDataDeleteBatchDTO, PaasFormEntityExt form) throws XbbException {
        lowCodeExecuteService(dataIdList, form.getSaasMark(), form.getBusinessType(), form.getId(), formDataDeleteBatchDTO.getCorpid());
        // 工作流，业务规则
        startWorkflow(formDataDeleteBatchDTO, form.getBusinessRules(), dataIdList);

    }

    @Override
    public void rollback(List<Long> list, String corpid) {

    }
}
